package com.i360day.invoker.configuration;

import com.i360day.invoker.AmqpHttpInvokerRequest;
import com.i360day.invoker.InvokerBasicConfiguration;
import com.i360day.invoker.NullRequestInterceptor;
import com.i360day.invoker.codes.decoder.Decoder;
import com.i360day.invoker.codes.encoder.Encoder;
import com.i360day.invoker.interceptor.HttpInvokerRequestInterceptor;
import com.i360day.invoker.properties.HttpInvokerProperties;
import com.i360day.invoker.registry.AmqpRemoteScanImportBeanDefinitionRegistrar;
import com.i360day.invoker.registry.RemoteScanDefinitionRegistryPostProcessor;
import com.i360day.invoker.request.HttpInvokerRequest;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liju.z
 */
@Configuration(proxyBeanMethods = false)
@ImportAutoConfiguration(InvokerBasicConfiguration.class)
public class AmqpInvokerAutoConfiguration {
    /**
     * <p> @author liju.z <p>
     *
     * <p> @Description 创建默认请求拦截器 <p>
     *
     * <p> @Date  21:03 <p>
     *
     * <p> @return HttpInvokerRequestInterceptor <p>
     **/
    @Bean
    @ConditionalOnMissingBean
    public HttpInvokerRequestInterceptor simpleRequestInterceptor() {
        return new NullRequestInterceptor();
    }

    /**
     * <p> @author liju.z <p>
     *
     * <p> @Description 创建默认request <p>
     *
     * <p> @Date  21:04 <p>
     **/
    @Bean
    @ConditionalOnMissingBean
    public HttpInvokerRequest defaultHttpInvokerClient(HttpInvokerProperties httpInvokerProperties, ConnectionFactory connectionFactory, Decoder decoder, Encoder encoder) {
        return new AmqpHttpInvokerRequest(connectionFactory, httpInvokerProperties);
    }

    @Bean
    @ConditionalOnMissingBean
    public RemoteScanDefinitionRegistryPostProcessor remoteBeanDefinitionRegistryPostProcessor() {
        return new RemoteScanDefinitionRegistryPostProcessor() {
            @Override
            public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
                setRegistrarFactory(new AmqpRemoteScanImportBeanDefinitionRegistrar(getResourceLoader(), getEnvironment()));
                super.postProcessBeanDefinitionRegistry(registry);
            }
        };
    }
}
